/**
 * jims
 */
package com.jims.master.modules.csm.service;

import com.jims.master.common.persistence.Page;
import com.jims.master.common.service.CrudService;
import com.jims.master.common.utils.PrintPdfUtils;
import com.jims.master.common.utils.StringUtils;
import com.jims.master.common.web.impl.BaseDto;
import com.jims.master.modules.csm.dao.ExpImportDetailDao;
import com.jims.master.modules.csm.entity.*;
import com.jims.master.modules.sys.dao.CompanyDao;
import com.jims.master.modules.sys.entity.User;
import com.jims.master.modules.sys.utils.DictUtils;
import com.jims.master.modules.sys.utils.UserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * 入库记录详情Service
 * @author zhuq
 * @version 2017-03-16
 */
@Service
@Transactional(readOnly = true)
public class ExpImportDetailService extends CrudService<ExpImportDetailDao, ExpImportDetail> {
    @Autowired
    private ExpImportDetailDao expImportDetailDao;
    @Autowired
    private ExpSupplierCataService expSupplierCataService;
    @Autowired
    private CompanyDao companyDao;
    @Autowired
    private ExpStorageDeptService expStorageDeptService;
    @Autowired
    private ExpInfoService expInfoService;


    public ExpImportDetail get(String id) {
        return super.get(id);
    }

    public List<ExpImportDetail> findList(ExpImportDetail expImportDetail) {
        return super.findList(expImportDetail);
    }

    public Page<ExpImportDetail> findPage(Page<ExpImportDetail> page, ExpImportDetail expImportDetail) {
        return super.findPage(page, expImportDetail);
    }

    @Transactional(readOnly = false)
    public int save(ExpImportDetail expImportDetail) {
        return super.save(expImportDetail);
    }

    @Transactional(readOnly = false)
    public int delete(ExpImportDetail expImportDetail) {
        return super.delete(expImportDetail);
    }

    //根据传来的expStock数据组装成expImportDetail数据
    public ExpImportDetail createData(ExpStock expStock,int itemNo,String importMasterId){
        ExpImportDetail expImportDetail=new ExpImportDetail();
        expImportDetail.setMasterId(importMasterId);		// 主表Id
        expImportDetail.setItemNo(String.valueOf(itemNo+1));	// 序号
        expImportDetail.setExpCode(expStock.getExpCode());		// 消耗品编码
        expImportDetail.setInfoId(expStock.getInfoId());		// expInfoId
        //判断大小包装,如果入库的是大包装规格,那么包装数量就是exp_info表的包装数量;如果入库的是小包装规格,那么包装数量是1
        if(expStock.getPackageSpec().trim().equals(expStock.getMinUnits().trim())){
            expImportDetail.setPackageNum("1");		// 包装数量
            Double number= expStock.getQuantity();
            expImportDetail.setQuantity(String.valueOf(number));		// 小包装库存量
        }else{
            expImportDetail.setPackageNum(expStock.getPackageNum());		// 包装数量
            Double number= expStock.getQuantity() * Integer.parseInt(expStock.getPackageNum());
            expImportDetail.setQuantity(String.valueOf(number));		// 小包装库存量
        }
        expImportDetail.setPackageSpec(expStock.getPackageSpec());		// 包装规格
        expImportDetail.setPackageUnits(expStock.getPackageUnits());		// 包装单位
        expImportDetail.setMinSpec(expStock.getMinSpec());		// 最小规格
        expImportDetail.setMinUnits(expStock.getMinUnits());		// 最小单位
        expImportDetail.setPurchasePrice(expStock.getPurchasePrice());		// 进货价
        expImportDetail.setDiscount(expStock.getDiscount());		// 折扣
        expImportDetail.setBatchNo(expStock.getBatchNo());		// 批号
        expImportDetail.setExpireDate(expStock.getExpireDate());		// 有效期
        expImportDetail.setSterilizationMethod(expStock.getSterilizationMethod());
        expImportDetail.setSterilizationBatchNo(expStock.getSterilizationBatchNo());
        expImportDetail.setSterilizationDate(expStock.getSterilizationDate());
        expImportDetail.updateOrgId();		// 机构ID
        expImportDetail.preInsert();
        return expImportDetail;
    }

    /**
     * 入库单据查询
     * @param page 分页对象
     * @param expImportDetail
     * @return
     */
    public Page<ExpImportDetail> findDetailsList(Page<ExpImportDetail> page, ExpImportDetail expImportDetail) {
        expImportDetail.updateOrgId();
        expImportDetail.setPage(page);

        ExpImportMaster expImportMaster = new ExpImportMaster();
        expImportMaster.updateOrgId();
        expImportMaster.setStorageId(UserUtils.getUser().getOrgDept().getId());  //当前科室
        expImportDetail.setExpImportMaster(expImportMaster);
        List<ExpImportDetail> list = expImportDetailDao.findDetailsList(expImportDetail);
        if(null != list && list.size() > 0){
            for (ExpImportDetail importDetail : list) {
                String newQuantity = Integer.parseInt(importDetail.getQuantity()) / Integer.parseInt(importDetail.getPackageNum()) + "";  //计算大包装入库数量
                importDetail.setQuantity(newQuantity);
            }
        }
        page.setList(list);
        return page;
    }

    /**
     * 入库单据查询---查询入库详情
     * @param expImportDetail
     * @return
     */
    public List<ExpImportDetail> findBymasterId(ExpImportDetail expImportDetail) {
        expImportDetail.updateOrgId();
        List<ExpImportDetail> list = dao.findDetailsList(expImportDetail);
        if(null != list && list.size() > 0){
            for (ExpImportDetail importDetail : list) {
                String newQuantity = Integer.parseInt(importDetail.getQuantity()) / Integer.parseInt(importDetail.getPackageNum()) + "";  //计算大包装入库数量
                importDetail.setQuantity(newQuantity);
            }
        }
        return list;
    }

    /**
     * 消耗品入库单据打印
     * @param expImportDetail
     * @return
     */
    public String expImportDetailsPrint(ExpImportDetail expImportDetail){
        User user = UserUtils.getUser();
        String deptId=null!=user.getOrgDept()?user.getOrgDept().getId():"";
        expImportDetail.setStorageId(deptId);
        List<BaseDto> list= dao.findDetailsListPrint(expImportDetail);
        ExpImportDetail entityForNum=dao.findNumByName(expImportDetail);
        int num=entityForNum.getNum();
        Map map = new HashMap();
        String hospital =UserUtils.getUser().getCompany().getOrgName();
        String title="消耗品入库凭证";
        Double tradePriceTotal=0.0;
        Double retailPriceTotal = 0.0;
        if (list.size() > 0) {
            BaseDto detail=list.get(0);
            map.put("storageName",detail.getAsString("storageName"));//收货库房
            map.put("importClass",DictUtils.getDictLabel(detail.getAsString("importClass"), "EXP_STOTARG_TYPE", ""));//入库类别
            map.put("documentNo",detail.getAsString("documentNo"));//入库单号
            map.put("importDate",detail.getAsString("importDate"));//入库日期
            map.put("accountType",DictUtils.getDictLabel(detail.getAsString("accountType"), "ACCOUNT_TYPE", ""));//付款方式
            if(StringUtils.isBlank(detail.getAsString("supplierJc"))){
                ExpStorageDept expStorageDept=expStorageDeptService.get(detail.getAsString("storageForm"));
                if(null!=expStorageDept){
                    map.put("receiver",expStorageDept.getStorageName());//发货库房
                }
                else {
                    map.put("receiver","");
                }
            }
            else {
                ExpSupplierCata expSupplierCata=expSupplierCataService.get(detail.getAsString("supplierJc"));
                if(expSupplierCata!=null){
                    map.put("receiver",expSupplierCata.getSupplierJc());//发货厂商
                }
                else{
                    map.put("receiver","");//发货厂商
                }
            }
//            if("1".equals(expImportDetail.getRemarks())){
//                map.put("receiver","");//发货厂商
//                map.put("storageName","");//收货库房
//            }
            int i=1;
            for(BaseDto detail1:list){
                detail1.put("minUnits",DictUtils.getDictLabel(detail.getAsString("minUnits"), "SPEC_UNIT", ""));
                detail1.put("index",Integer.toString(i++));
                detail1.put("expireDate",detail1.getAsString("expireDate"));
                Double totalTrade=Double.parseDouble(detail1.getAsString("tradePrice"))*Double.parseDouble(detail1.getAsString("quantity"));
                Double totalRetail=Double.parseDouble(detail1.getAsString("retailPrice"))*Double.parseDouble(detail1.getAsString("quantity"));
                detail1.put("totalTrade",String.format("%.2f", totalTrade));
                detail1.put("totalRetail",String.format("%.2f",totalRetail));
                tradePriceTotal+=totalTrade;
                retailPriceTotal+=totalRetail;
            }
        }
        map.put("hospital",hospital);
        map.put("lists",list);
        map.put("title",title);
        map.put("num",num);//品种数量
        map.put("tradePriceTotal",String.format("%.2f", tradePriceTotal));
        map.put("retailPriceTotal",String.format("%.2f", retailPriceTotal));
        String printPath = PrintPdfUtils.previewPdf(user.getId(), "his/csm/expImportDetailsPrint.jasper", map, list, "expImportDetailsPrint");
        return  printPath;
    }
}